package io.netty;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * @author verlet
 * @date 2020/2/29
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 创建成功，开始发送消息");
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        ByteBuf in = (ByteBuf) msg;
        try {
//            System.out.println(in.toString(CharsetUtil.UTF_8));
            System.out.println(Thread.currentThread() + " ==> " + msg);
            ChannelFuture channelFuture = ctx.writeAndFlush("消息回馈！$_");
//            ctx.channel().eventLoop().execute(()->{});
//            ctx.channel().eventLoop().schedule()
//            ChannelFuture channelFuture = ctx.writeAndFlush(Unpooled.copiedBuffer("消息回馈！".getBytes()));
            // 添加监听，消费发送到对方完成，客户端就断开连接
            channelFuture.addListener(ChannelFutureListener.CLOSE);
            // 原消息往下传
           ctx.fireChannelRead(msg);

        } finally {
            // 当存在write时HeadContext释放。 fireChannelRead 往下执行，不能释放。
            // ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 读取完毕。。。");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 出现异常关闭
        cause.printStackTrace();
        ctx.close();
    }
}
